package com.henz.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.henz.web.util.ChannelUtil;

@Controller
@RequestMapping("/channel")
public class ChannelController {
	
	Log logger = LogFactory.getLog(this.getClass());
	
	@RequestMapping("/token.json")  
	public @ResponseBody Map<String, Object> getToken( 
		@RequestBody Map<String, Object> paramMap 
	) throws Exception{
		Map<String, Object> returnValue = null;
		
		ChannelService channelService = null;
		String channelId = null;
		String token = null;
		
		channelId = (String)paramMap.get("channelId");
		
		returnValue = new HashMap<String, Object>();
		
		channelService = ChannelServiceFactory.getChannelService();
		token = channelService.createChannel(channelId);
		
		returnValue.put("token", token);
		
		return returnValue;
	}
	
	@RequestMapping("/sendChannel.json")
	public @ResponseBody String sendChat(
		@RequestBody Map<String, Object> paramMap
	)throws Exception{
		String channelId = null;
		String msg = null;
		channelId = (String)paramMap.get("channelId");
		msg = (String)paramMap.get("message");
		logger.info("Message[" + msg + "]");
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		//channelService.sendMessage(new ChannelMessage(channel, URLEncoder.encode(msg, "UTF-8")));
		//channelService.sendMessage(new ChannelMessage(channelId, msg));
		channelService.sendMessage(ChannelUtil.getChannelMessage(channelId, msg));
		return "";
	}
	
}